//
//  XMLHelper.m
//  iJobsXcode
//
//  Created by Nguyen Minh Khoai on 1/14/13.
//
//

#import "XMLHelper.h"
#import "NSMutableArray+Shuffle.h"
#import <objc/runtime.h>

id updateObjPropertyFromXML(id object, NSString *attribute, GDataXMLElement *element, NSString *elementName) {
    id result = [object objectForKey:attribute];
    
    /* detect attribute type */
    objc_property_t property = class_getProperty([object class], [attribute UTF8String]);
    const char *attributeType = property_getAttributes(property);
    NSString *attributeName = @(attributeType);
    
    /* get element value */
    NSString *value = [XMLHelper stringValueFromElement:element andName:elementName];
    
    if(value.length > 0) {
        if([attributeName containString:NSStringFromClass([NSString class])]) {
            result = value;
        } else if ([attributeName containString:NSStringFromClass([NSNumber class])]) {
            result = @(value.integerValue);
        } else if ([attributeName containString:NSStringFromClass([NSDate class])]) {
            result = [DateHelper dateFromString:value];
        } else {
            result = value;
        }
    }
    return result;
}

@implementation XMLHelper

- (id)init {
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

#pragma mark - Utility methods

+ (NSArray *)elementsFromResponseData:(NSData *)data
                               atPath:(NSString *)xmlPathString
                                error:(NSError **)error {
    NSError *parseError = nil;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data options:0 error:&parseError];
    if(!parseError) {
        NSArray *nodes = [doc nodesForXPath:xmlPathString error:error];
        if(!parseError && [nodes count] > 0) {
            return nodes;
        }
    }
    
    *error = parseError;
    return nil;
}

+ (GDataXMLElement *)firtElementFromResponseData:(NSData *)data
                                          atPath:(NSString *)xmlPathString
                                           error:(NSError **)error {
    GDataXMLElement *firstElement = nil;
    NSArray *notes = [XMLHelper elementsFromResponseData:data atPath:xmlPathString error:error];
    if(notes.lastObject) {
        firstElement = notes[0];
    }
    return firstElement;
}

+ (NSString *)stringValueFromElement:(GDataXMLElement *)element andName:(NSString *)name {
    GDataXMLElement *temp = (GDataXMLElement *)[element elementsForName:name][0];
    return temp.stringValue;
}

@end
